<template>
  <div v-if="page === 'cart'" id="cart">
    <div v-if="books.length">
      <!-- 购物车内容列表 -->
      <table border="1" align="center" width="500">
        <caption>
          <h2>购物车</h2>
        </caption>
        <tr>
          <th colspan="6">
            <button @click="buy">继续购物</button>
          </th>
        </tr>
        <tr>
          <th></th>
          <th>名称</th>
          <th>价格</th>
          <th>数量</th>
          <th>小计</th>
          <th>操作</th>
        </tr>
        <tbody>
          <tr v-for="(item, index) in books" :key="index" align="center">
            <td>{{ item.id }}</td>
            <td>{{ item.name }}</td>
            <td>{{ filter(item.price) }}</td>
            <td>
              <button
                @click="decrement(index)"
                v-bind:disabled="item.count <= 0"
              >
                -
              </button>
              {{ item.count }}
              <button @click="increment(index)">+</button>
            </td>
            <td>
              {{ filter(item.price * item.count) }}
            </td>
            <td>
              <button @click="removeHandle(index)">移除</button>
            </td>
          </tr>
          <tr align="center">
            <td colspan="3">总价格</td>
            <td colspan="3">{{ filter(computedName) }}</td>
          </tr>
        </tbody>
      </table>
    </div>
    <div v-else>
      <h2>购物车为空</h2>
      <button @click="buy">继续购物</button>
    </div>
  </div>

  <div v-if="page === 'buy'" id="buy">
    <table border="1" align="center" width="500">
      <caption><h2>商品界面</h2></caption>
      <th>
        <input type="checkbox" id="all" @click="checkAll" v-model="checked"/>
        <label for="all">全选</label>
      </th>
      <th>名称</th>
      <th>价格</th>
      <tr v-for="(item, index) in goods" :key="index" align="center">
        <td>
          <input type="checkbox" :id="item.name" :value="item.name" v-model="checkedNames" />
        </td>
        <td>{{ item.name }}</td>
        <td>{{ item.price }}</td>
      </tr>
      <tr>
        <td colspan="5" align="center">
          <button @click="addToCart">加入购物车</button>
        </td>
      </tr>
    </table>
    {{ checkedNames }}
  </div>
</template>

<script>
import { reactive, toRefs } from "@vue/reactivity";
import { computed, onMounted, watch } from "@vue/runtime-core";
export default {
  setup() {
    const state = reactive({
      page: 'cart',
      books: [],
      goods:[],
      checked: false,
      checkedNames: []
    });

    // 数据读取
    onMounted(() => {
      fetch('/class4/test4-9.json')
      .then(res=>res.json())
      .then(res=>{
        state.goods=res.goods
      })
    })

    // 减去
    const decrement = (index) => {
      state.books[index].count--;
    };

    // 加上
    const increment = (index) => {
      state.books[index].count++;
    };

    // 去掉商品
    const removeHandle = (index) => {
      let n = state.checkedNames.indexOf(state.books[index].name)
      state.checkedNames.splice(n, 1)
      state.books.splice(index, 1);
      for (let i = 0; i < state.books.length; i++) {
        state.books[i].id = i + 1;
      }
    };

    const filter = (price) => {
      return '￥' + price.toFixed(2);
    };

    // 转换到购物界面
    const buy = () => {
      state.page = 'buy'
      state.checkedNames = []
      for(let n = 0;n < state.books.length;n++){
        state.checkedNames.push(state.books[n].name)
      }
    }

    const computedName = computed(() => {
      let totalPrice = 0;
      for (let i = 0; i < state.books.length; i++) {
        totalPrice += state.books[i].price * state.books[i].count;
      }
      return totalPrice;
    });

    // 全选框实现
    const checkAll = () => {
      if(state.checked) {
        state.checkedNames = []
      }else{
        state.goods.forEach((item) => {
          if(state.checkedNames.indexOf(item.name) == -1) {
            state.checkedNames.push(item.name)
          }
        })
      }
    }

    // 获取列表商品名列表
    const getNameList = (list) => {
      let re = []
      for(let n = 0;n < list.length;n++){
        re.push(list[n].name)
      }
      return re
    }

    // 加入购物车
    const addToCart = () => {
      for(let n = 0;n < state.checkedNames.length;n++){
        if(getNameList(state.books).indexOf(state.checkedNames[n]) == -1){
          state.books.push(
            {
              id: state.books.length + 1,
              name: state.checkedNames[n],
              price: state.goods[getNameList(state.goods).indexOf(state.checkedNames[n])].price,
              count: 1
            })
        }
      }
      state.page='cart'
    }

    // 同步全选框与各个商品选择框
    watch(
      () => state.checkedNames, (newVal, oldVal) => {
        if(newVal.length === state.goods.length){
          state.checked = true
        }
        else{
          state.checked = false
        }
      }
    )

    return {
      ...toRefs(state),
      decrement,
      increment,
      removeHandle,
      filter,
      computedName,
      checkAll,
      addToCart,
      buy
    };
  },
};
</script>
